package service

import (
	"context"
	"gf2DemoServer/internal/dao"
	"gf2DemoServer/internal/model"
	"gf2DemoServer/internal/model/do"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/text/gstr"
	"time"
)

type sCategory struct{}

var insCategory *sCategory

func Category() *sCategory {
	if insCategory == nil {
		insCategory = &sCategory{}
	}
	return insCategory
}

// Add 添加
func (s *sCategory) Add(ctx context.Context, in *model.CategoryAddInput) (insertId int64) {
	insert, err := dao.Category.Ctx(ctx).Insert(&do.Category{
		Title:      gstr.Trim(in.Title),
		Thumb:      in.Thumb,
		Sort:       in.Sort,
		Status:     in.Status,
		CreateTime: time.Now().Unix(),
	})
	if err != nil {
		return 0
	}
	id, err := insert.LastInsertId()
	if err != nil {
		return 0
	}
	return id
}

// Del 删除
func (s *sCategory) Del(ctx context.Context, ids string) bool {
	result, err := dao.Category.Ctx(ctx).WhereIn(dao.Category.Columns().Id, ids).Delete()
	if err != nil {
		return false
	}
	affected, err := result.RowsAffected()
	if err != nil {
		return false
	}
	return affected > 0
}

// Update 添加
func (s *sCategory) Update(ctx context.Context, in *model.CategoryUpdateInput) bool {
	affected, err := dao.Category.Ctx(ctx).Where(do.Category{
		Id: in.Id,
	}).UpdateAndGetAffected(do.Category{
		Title:      gstr.Trim(in.Title),
		Thumb:      in.Thumb,
		Sort:       in.Sort,
		Status:     in.Status,
		UpdateTime: time.Now().Unix(),
	})
	if err != nil {
		return false
	}
	return affected > 0
}

// List 列表
func (s *sCategory) List(ctx context.Context, in *model.CategoryListInput) (list []*model.CategoryListItem, count int) {
	c := dao.Category.Columns()
	m := dao.Category.Ctx(ctx)
	if !g.IsEmpty(in.Title) {
		m = m.WhereLike(c.Title, `%`+in.Title+`%`)
	}
	err := m.Page(in.Page, in.Limit).Order(c.Id, "DESC").Scan(&list)
	if err != nil {
		return nil, 0
	}
	count, err = m.Count()
	if err != nil {
		return nil, 0
	}
	return
}

// Detail 详情
func (s *sCategory) Detail(ctx context.Context, id int) (info *model.CategoryDetail) {
	err := dao.Category.Ctx(ctx).Where(do.Category{
		Id: id,
	}).Scan(&info)
	if err != nil {
		return nil
	}
	return
}
